// packagBuy/pages/found/encyclopedia/encyclopedia.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import {
  foundApi
} from '../../../../config/config'
const getURL = require('../../../../utils/util') //引入配置接口文件
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    isShowPartnerAll:true,
    statusBarHeight: app.globalData.statusHeight,
    categoryData: [], //类目
    selectedCategory: [], //已选择类目{id:一级分类ID,sonId:[二级分类ID]}
    sonCategoryIds: [], //已选择的二级分类ID
    listData: [],
    page: 1,
    rows: 8,
    nomoreData: false,
    showPop: false,
    fitmentId: '', //储存点击装修前等的ID，用户显示点击状态
    authorizationPopup: false
  },
   // 展示合伙人二维码
   partnerCode: function(e) {
    const codeImg = e.target.dataset.url
    wx.previewImage({
      urls: [codeImg],
      current: codeImg // 当前显示图片的http链接
    })
  },
  // 关闭合伙人二维码
  closeCodePop: function() {
    this.setData({
      showPartnerCodePop: false
    })
  },
  // 拨打合伙人电话
  partnerPhone: function() {
    const that = this
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone
    })
  },
 // 展开合伙人信息
 showPartnerAll: function() {
  this.setData({
    isShowPartnerAll:!this.data.isShowPartnerAll
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    this.getCategoryList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    //保存访问足迹
    app.saveAccessFootprint(this.data.footprintGuid, 'encyclopedia', 0)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.nomoreData) {
      this.setData({
        page: this.data.page + 1
      })
      this.getListData()
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  // 获取优惠券列表数据
  getCategoryList() {
    let params = {
      page: 1,
      rows: 20,
    }
    app.reqFun.requestForm('POST', foundApi.queryEncyCategory, params, (response) => {
      if (response.data) {
        const res = response.data
        if (res.success == 1 && res.data && res.data.records && res.data.records.length) {
          const list = res.data.records[0].childList || []
          list.forEach(v => {
            v.selected = false
          })
          const selectedCategory = list.map(v => {
            return {
              id: v.id,
              name: v.name,
              sonId: '',
              sonName: '',
              selected:true
            }
          })
          this.setData({
            categoryData: list,
            selectedCategory
          })
          this.getListData()
        }
      }
    })
  },
  // 获取优惠券列表数据
  getListData() {
    let fatherCategoryIds = [];
    let sonCategoryIds = [];
    if (this.data.fitmentId !== '') {
      fatherCategoryIds.push(this.data.fitmentId);
      sonCategoryIds = [];
    } else {
      const selectedCategory = this.data.selectedCategory
      selectedCategory.forEach(v => {
        sonCategoryIds = sonCategoryIds.concat(v.sonId || [])
        fatherCategoryIds=fatherCategoryIds.concat(v.selected?[v.id]:[])
      })
    }
    
    let params = {
      // page: this.data.page,
      // rows: this.data.rows,
      paramsRaw: null
    }
    if(fatherCategoryIds.length){
      params.paramsRaw=JSON.stringify({
        fatherCategoryIds,
        sonCategoryIds
      })
    }else{
      params.paramsRaw=JSON.stringify({
        sonCategoryIds
      })
    }

    app.reqFun.requestForm('POST', foundApi.queryEncyclopediaHome, params, (response) => {
      if (response.data) {
        const res = response.data
        if (res.success == 1) {
          const records = res.data || []
          records.forEach(v => {
            const list = v.contents.map((con, index) => {
              return {
                ...con,
                ...{
                  hot: index === 0,
                  pic: getURL.getImgUrl(con.pic)
                }
              }
            })
            v.contents = list
          })
          this.setData({
            listData: records, //this.data.page === 1 ? records : this.data.listData.concat(records),
            nomoreData: true // records.length < this.data.rows
          })
        }
      }
    })
  },
  // 展开筛选
  openConditonPop() {
    this.setData({
      showPop: true
    })
  },
  // 关闭筛选
  closePop() {
    // 设置筛选条件选中项
    /* const paramCate = this.data.selectedCategory
    const lists = this.data.categoryData
    lists.forEach(cate => {
      let childId = ''
      const temp = paramCate.filter(parent => parent.id == cate.id)
      if (temp && temp.length) {
        childId = temp[0].sonId || ''
      }
      cate.childList && cate.childList.forEach(child => {
        child.selected = child.id == childId
      })
      cate.selected = !childId
    }) */
    this.setData({
      //categoryData: lists,
      showPop: false
    })
  },
  // 选择二级分类，更改当前所选分类选中状态
  selectedSort(e) {
    const id = e.currentTarget.dataset.id
    const parentId = e.currentTarget.dataset.pid
    const lists = this.data.categoryData
    lists.forEach(cate => {
      if (cate.id == parentId) {
        cate.selected = cate.selected ? false : !id;
        cate.childList && cate.childList.forEach(child => {
          child.selected = child.selected ? false : child.id == id
        })
      }
    })
    this.setData({
      categoryData: lists
    })
  },
  // 确定搜索
  handleSearch() {
    const list = this.data.categoryData
    const selectedCategory = list.map(cate => {
      const selectedChild = cate.childList.filter(child => !!child.selected)
      return {
        id:cate.id,
        name: cate.name,
        selected:cate.selected,
        sonId: selectedChild && selectedChild.length ? selectedChild[0].id : '',
        sonName: selectedChild && selectedChild.length ? selectedChild[0].name : ''
      }
    })
    this.setData({
      selectedCategory,
      fitmentId: ''
    })
    this.closePop()
    this.getListData()
  },
  toSortList(e) {
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    wx.navigateTo({
      url: '../encyclopediaList/encyclopediaList?id=' + id + '&name=' + name,
    })
  },

  //直接点击bar的装修前。。。
  search(e) {
    let fitmentId = e.currentTarget.dataset.item;
    if (this.data.fitmentId === fitmentId) {
      fitmentId = ''
    }
    let categoryData = this.data.categoryData.map(val => {
      if (val.id === fitmentId) {
        val.selected = true;
      } else if (fitmentId === '') {
        val.selected = true;
      } else {
        val.selected = false;
      }
      val.childList.forEach(val => {
        val.selected = false;
      });
      return val
    });
    this.setData({
      fitmentId,
      categoryData
    });
    this.getListData()
  }
})
